

import UIKit


class RepairViewController: UIViewController {
    
    // ----------------外界调用的属性值--------------
    var valueBlock: valueBlock?
    /// cell内容
    //    var originObj = [String:Any]()
    var originObj : [RepairDetail] = []
 
    /// cell字体颜色
    var cellTitleColor = UIColor.green
        var titleString: String? = "维修选项"
    /// cell字体大小
    var cellTitleFont: CGFloat = 17
    /// 标题
    /// 标题字体大小
    var titleFont: CGFloat = 15
    var selectIndex : Int = 0;
    
    // ---------------内部属性-------------------
    typealias valueBlock = (Array<Any>)->Swift.Void
    fileprivate var tableView = UITableView()
    fileprivate var overVeiw = UIView()
    fileprivate let cellID = "cellID"
    fileprivate var tableViewHight: CGFloat {
        return CGFloat(originObj.count) * rowHight + headerViewHight + footerViewHight
    }
    fileprivate let rowHight: CGFloat = 60
    fileprivate let headerViewHight: CGFloat = 40
    fileprivate var footerViewLineHight: CGFloat = 5
    fileprivate var footerViewHight: CGFloat {
        return headerViewHight + footerViewLineHight
    }
    
    required init( originObj: [RepairDetail]) {
        self.originObj = originObj
        super.init(nibName: nil, bundle: nil)
        view.backgroundColor = UIColor.clear
        self.providesPresentationContextTransitionStyle = true
        self.definesPresentationContext = true
        self.modalPresentationStyle = .custom
        
        // 初始化UI
        //        setupUIViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        UIView.animate(withDuration: 0.25) {
            var frame = self.tableView.frame
            frame.origin.y = kScreenHeight-self.tableViewHight
            self.tableView.frame = frame
            self.overVeiw.alpha = 0.5
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

// MARK: 初始化UI
extension RepairViewController {
    func setupUIViews() {
        overVeiw =
            UIView(frame: CGRect(x: 0, y: 0, width:kScreenWidth, height: kScreenHeight))
        overVeiw.backgroundColor = UIColor.black
        overVeiw.alpha = 0.0
        view.addSubview(overVeiw)
        tableView.alpha = 1
        tableView = UITableView(frame: CGRect(x: 0, y: kScreenHeight, width: kScreenWidth, height: tableViewHight), style: .plain)
        tableView.separatorStyle =  UITableViewCell.SeparatorStyle.none
        view.addSubview(tableView)
        tableView.layer.masksToBounds = true
        tableView.layer.cornerRadius = 8
        tableView.snp.makeConstraints {
            $0.top.equalToSuperview().offset(screenHeight/2 - tableViewHight/2 )
            $0.left.equalTo(30)
            $0.right.equalTo(-30)
            $0.height.equalTo(tableViewHight)
        }
        tableView.delegate = self
        tableView.dataSource = self
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.isScrollEnabled = false
        tableView.bounces = false
        tableView.isPagingEnabled = false
        //self.demoList.separatorStyle = UITableViewCellSeparatorStyle.None
        let nib = UINib(nibName: "RepairViewCell", bundle: nil) //nibName指的是我们创建的Cell文件名
        tableView.register(nib, forCellReuseIdentifier: cellID)
    }
}

// MARK: 点击屏幕弹出退出
extension RepairViewController {
    
    func sheetViewDismiss() {
        UIView.animate(withDuration: 0.25, animations: {
            var frame = self.tableView.frame
            frame.origin.y = kScreenHeight
            self.tableView.frame = frame
            self.overVeiw.alpha = 0
            
        }) { (_) in
            self.dismiss(animated: false, completion: nil)
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        sheetViewDismiss()
    }
    
    @objc func cancelBtnDidClick(btn: UIButton) {
        sheetViewDismiss()
    }
}

// MARK: UITableViewDelegate, UITableViewDataSource
extension RepairViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return originObj.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! RepairViewCell
        //        cell.payName.text = "dsfadsfadfas"
       
        cell.model = originObj[indexPath.row]
        cell.addTap = { [weak self] (id,index) in
            self!.originObj[indexPath.row].number += 1
            self?.tableView.reloadData()
        }
        cell.reduceTap = { [weak self] (id,index) in
            if self!.originObj[indexPath.row].number > 1 {
                self!.originObj[indexPath.row].number -= 1
                self?.tableView.reloadData()
            }
        }
        return cell
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CGFloat(rowHight)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //判断该行原先是否选中
        selectIndex = indexPath.row
        ////刷新该行
        self.tableView.reloadData()
        //        tableView.deselectRow(at: indexPath, animated: true)
        //
        //        if (self.valueBlock != nil) {
        //            self.valueBlock!(indexPath.row)
        //        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return headerViewHight
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return headerViewHight + 5
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
        // 标题
        let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: (screenWidth - 40), height: headerViewHight))
        titleLabel.text = titleString
        titleLabel.font = UIFont.big
        titleLabel.textColor = UIColor.colBlack
        titleLabel.textAlignment = .center
       
 
        return titleLabel
        
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = Bundle.main.loadNibNamed("RepairFooter", owner: self, options: nil)?[0] as! RepairFooter
        //        footerView
        footerView.CancelTap = { [weak self]  in
            self!.dismiss(animated: false, completion: nil)
        }
        footerView.tap = { [weak self]  in
            let obj = self!.originObj
            var param : [[String:Any]] = []
            for item in obj {
                 param.append(["id":item.id,"number":item.number])
            }
             self!.valueBlock!(param)
           

        }

        return footerView;
    }
}
